package com.papercutting.platform.interceptor;

import com.papercutting.platform.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String path = request.getRequestURI();
        System.out.println("请求路径: " + path);
        
        // 允许匿名访问的路径
        if (path.startsWith("/api/auth/login") || 
            path.startsWith("/api/auth/web-login") ||
            path.startsWith("/api/health") || 
            path.startsWith("/api/info")) {
            System.out.println("允许匿名访问的路径");
            return true;
        }
        
        // 从请求头中获取token
        String authorizationHeader = request.getHeader("Authorization");
        System.out.println("Authorization头: " + authorizationHeader);
        
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            try {
                String token = authorizationHeader.substring(7);
                System.out.println("解析的token: " + token);
                // 验证token有效性
                String username = jwtUtil.getUsernameFromToken(token);
                System.out.println("从token中获取的用户名: " + username);
                if (username != null) {
                    // 将用户ID添加到请求属性中
                    Long userId = jwtUtil.getUserIdFromToken(token);
                    System.out.println("从token中获取的用户ID: " + userId);
                    request.setAttribute("userId", userId);
                    return true;
                }
            } catch (Exception e) {
                System.out.println("Token解析异常: " + e.getMessage());
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("{\"code\":401,\"message\":\"Token无效或已过期\"}");
                return false;
            }
        }
        
        // 未提供token或token无效
        System.out.println("未提供token或token无效");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("{\"code\":401,\"message\":\"请先登录\"}");
        return false;
    }
}